﻿using Huirui.Cavan.Domain.MainBoundedContext.SearchModule;
using Huirui.Cavan.Domain.MainBoundedContext.SystemModule;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Huirui.Cavan.Domain.Seedwork;
using Spring.Context.Support;
using Huirui.Cavan.Core.Extension;

namespace Huirui.Cavan.Application.MainBoundedContext.SystemModule
{
    public class SystemConfigAppService : BaseAppService<SystemConfig, SystemConfigSearch, ISystemConfigRepository>, ISystemConfigAppService
    {
        private IEmployeeAppService EmployeeAppService { get; set; }

        #region IAccountAppService Members

        public BoolGenericResult<SystemConfig> Edit(SystemConfig entity)
        {
            this.SpringContext = ContextRegistry.GetContext();
            BoolGenericResult<SystemConfig> result = new BoolGenericResult<SystemConfig>();
            if (entity.IsNull())
            {
                throw new ArgumentNullException("");
            }
            this.EmployeeAppService = this.SpringContext.GetObject(SystemModuleConst.EMPLOYEEAPPSERVICE) as IEmployeeAppService;
            Employee employee = this.EmployeeAppService.GetBySearch(SearchFactory.CreateEmployeeSearch(SecurityAppService.UserAccount.Id)).FirstOrDefault();
            Administrator admin = new Administrator(employee);

            SystemConfig oldSystemConfig = this.Repository.Get(entity.Id);
            if (oldSystemConfig.IsNull())
            {
                result = admin.AddSystemConfig(entity.Type, entity.Item, entity.Value, entity.DataType, entity.Description, entity.Remark);
                if (result.IsSuccess)
                    return base.Add(result.Object);
            }
            else
            {
                result = admin.UpdateSystemConfig(oldSystemConfig, entity.Value, entity.Remark);
                if (result.IsSuccess)
                    return base.Update(result.Object);
            }
            return result;
        }

        #endregion
    }
}
